package com.sniper.springmvc.shiro.session.redis;

import com.sniper.springmvc.redis.JedisConnectionFactory;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class RedisCacheManager implements CacheManager {

    // fast lookup by name map
    private final ConcurrentMap<String, MyCache> caches = new ConcurrentHashMap<>();

    /**
     * The Redis key prefix for the sessions
     */
    private String keyPrefix = "shiro_redis_session:";

    private JedisConnectionFactory cache;
    private long ttlTime = 180000;


    public void setCache(JedisConnectionFactory cache) {
        this.cache = cache;
    }

    public void setTtlTime(long ttlTime) {
        this.ttlTime = ttlTime;
    }

    /**
     * Returns the Redis session keys prefix.
     *
     * @return The prefix
     */
    public String getKeyPrefix() {
        return keyPrefix;
    }

    /**
     * Sets the Redis sessions key prefix.
     *
     * @param keyPrefix The prefix
     */
    public void setKeyPrefix(String keyPrefix) {
        this.keyPrefix = keyPrefix;
    }

    @Override
    public <K, V> MyCache<K, V> getCache(String name) throws CacheException {

        MyCache c = caches.get(name);
        if (c == null) {
            // create a new cache instance
            c = new RedisCache<K, V>(cache, ttlTime, keyPrefix);

            // add it to the cache collection
            caches.put(name, c);
        }
        return c;
    }
}